package Commands;

import GPIO.GPIOControl;

public class PINCmd extends Command {

	private boolean request = false;
	private boolean on = false;
	private int pin = -1;
	private String result = "";

	public PINCmd() {
		commandString = "PIN";
	}

	@Override
	public void execute() throws Exception {
		if (request) {
			result = "PIN " + String.valueOf(pin) + " "
					+ String.valueOf(GPIOControl.getPinOut(pin));
			
			request = false;
		} else {
			GPIOControl.setPinOut(pin, on);
		}
	}

	@Override
	public void validateOptions(String options) throws Exception {
		String[] parameters = options.split(" ");
		if (parameters.length < 2) {
			throw new Exception("Invalid parameters for Command");
		}

		// Set Pin
		pin = Integer.parseInt(parameters[0]);

		if (parameters[1].compareTo("?") == 0) {
			// Get PinState
			request = true;
		} else {
			// Set PinState
			on = (Integer.parseInt(parameters[1]) == 1);
			request = false;
		}
	}

	@Override
	public String getResult() {
		String ret = result;
		result = "";
		return ret;
	}
}
